<template>
  <div>
    <editor id="tinymceEditor" :init="tinymceInit" v-model="content" :key="tinymceFlag" api-key="f1pgzwg79ie3fd6n09nm8xch6u0e3i6b24yb4qqf4pyswory"></editor>
  </div>
</template>
<script>
import Editor from '@tinymce/tinymce-vue'
import { uploadImg } from "@/api/PC-Home.js";
import axios from "axios"
export default {
  name: 'TinymceEditor',
  props: {
    defaultContent: {
      type: String,
      default: '',
    },
    height: {
      type: Number,
      default: 500,
    },
    width: {
      type: Number,
      default: undefined,
    },
    showMenubar: {
      type: Boolean,
      default: true,
    },
    toolbar: {
      type: String,
      default: ` undo redo
      | formatselect fontselect fontsizeselect lineheight
      | bold italic underline strikethrough forecolor backcolor formatpainter
      | insertdatetime superscript subscript hr
      | link image media | alignleft aligncenter alignright alignjustify
      | numlist bullist outdent indent
      | removeformat
      | preview fullscreen code`,
      
    },
  },
  components: {
    Editor,
  },
  data() {
    return {
      content: '',
      tinymceFlag: 1,
      tinymceInit: {},
    }
  },
  created() {
    let _that = this
    this.tinymceInit = {
      language: 'zh_CN',
      height: this.height,
      branding: true, // 去水印
      statusbar: false, // 隐藏编辑器底部的状态栏
      elementpath: false, // 禁用编辑器底部的状态栏
      toolbar: this.toolbar,
      paste_data_images: true, // 允许粘贴图像
      browser_spellcheck: true, // 拼写检查
      menubar: this.showMenubar, // 隐藏最上方menu
      // plugins: `print fullpage searchreplace autolink directionality visualblocks
      //   visualchars template codesample charmap hr pagebreak nonbreaking anchor toc insertdatetime
      //   wordcount textpattern help advlist table lists paste preview fullscreen image imagetools code link`,
      plugins: `advlist autolink lists link image charmap print preview anchor,
        searchreplace visualblocks code fullscreen,
        insertdatetime media table paste help wordcount image`,
      async images_upload_handler(blobInfo,success,failure) {
        // const file = new File([blobInfo.blob()], blobInfo.filename(), {
        //   type: 'image/*',
        // })
        var formData = new FormData();
        formData.append('file',blobInfo.blob(), blobInfo.filename());
        uploadImg(formData).then(res => {
          if (res.code === 200) {
            _that.$message.success("上传成功");
            let imageUrl = res.data
            let index = imageUrl.lastIndexOf('/imgUpload')
            let url = imageUrl.substring(index,imageUrl.length)
            success( process.env.VUE_APP_URL + url)
          } else {
            _that.$message.error(res.message);
          }
        }).catch(err => failure(err))
        // post('cms/file', { file })
        //   .then(res => {
        //     if (res.length && res[0]?.url) {
        //       success(res[0].url)
        //     }
        //   })
        //   .catch(err => failure(err))
      },
      file_picker_types: 'media',
        file_picker_callback: (callback, value, meta) => {
          if (meta.filetype === 'media') {
            const input = document.createElement('input')
            input.setAttribute('type', 'file')
            const that = this // 为 Vue 构造函数中的 this，指向 Vue 实例对象
            input.onchange = async function () {
              const file = this.files[0] // 为 HTMLInputElement 构造函数中的 this，指向 input 实例对象
              const isValid = await that.validateVideo(file)

              if (isValid) {
                const { url } = await that.uploadFile(file, 'video')
                callback(url)
              } else {
                callback()
              }
            }

            input.click()
          }
        },
        video_template_callback: data => {
          return `<video width="745" height="420" controls="controls" src=${data.source} />`
        }
    }
  },
  mounted() {
    if (this.defaultContent) {
      this.content = this.defaultContent
    }
  },
  watch: {
    content: {
      handler() {
        this.$emit('change', this.content)
      },
    },
    defaultContent: {
      handler() {
        this.content = this.defaultContent
      },
      immediate: true,
    },
  },
  methods:{
    /**
     * @description 校验上传视频
     * @param {File} file - 要上传的文件
     * @returns {boolean}
     */
    async validateVideo (file) {
      const isMP4 = file.type === 'video/mp4'
      // const isLt3M = file.size / 1024 / 1024 < 3

      if (!isMP4) {
        this.$message.error('上传视频必须为 MP4 格式！')

        return false
      }

      // if (!isLt3M) {
      //   this.$message.error('上传视频大小限制 3M 以内！')

      //   return false
      // }

      // const duration = await this.getVideoDuration(file)
      // if (duration > 60) {
      //   this.$message.error('上传视频时长不能超过 60 秒！')

      //   return false
      // }

      return true
    },

    /**
     * @description 获取视频时长
     * @param {File} file - 要上传的文件
     * @returns {Promise<number>}
     */
    getVideoDuration (file) {
      return new Promise(resolve => {
        const videoElement = document.createElement('video')
        videoElement.src = URL.createObjectURL(file)

        videoElement.addEventListener('loadedmetadata', () => {
          resolve(videoElement.duration)
        })
      })
    },

    /**
     * @description 上传文件
     * @param {File} file - 要上传的文件
     * @param {string} folder - 所存放的文件夹
     * @returns {Object}
     */
    async uploadFile (file, folder) {
      const form = new FormData()
      form.append("file", file);
      form.append("folder", folder);
      // 注：此为调用后端上传接口，需根据实际情况进行调整
      const { data } = await axios({
        method: 'POST',
        url: '/menu/uploadImg',
        data: form,
        headers: { 'Content-Type': 'multipart/form-data' }
      })
       let index = data.data.lastIndexOf('/imgUpload')
      let url = data.data.substring(index,data.data.length)
      return {
        url: process.env.VUE_APP_URL + url,
        name: file.name
      }
    }
  },
  activated() {
    this.tinymceFlag++
  }
}
</script>

<style lang="scss">
.tox-notification {
  display: none !important;
}
</style>
